<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\utils;

use app\shop_admin\model\Distribution;
use app\shop_admin\model\Order;
use PhpOffice\PhpSpreadsheet\Reader\Xls\MD5;
use think\Exception;
use think\facade\Request;

class Dada
{
    private $appKey;
    private $appService;
    private $sourceId;
    //测试域名：newopen.qa.imdada.cn
    //线上域名：newopen.imdada.cn
    private $baseUrl = "http://newopen.qa.imdada.cn";

    public function __construct($data = null)
    {
        global $user;
        $res = Distribution::where('mall_id', $user->mall_id)->where('third_party', 2)
            ->where('merchant_id', $user->merchant_id)
            ->find();
        if (is_null($res) && !is_null($data)) {
            $config = json_decode($data['config']);
            $this->appKey = $config[0]->app_key;
            $this->appService = $config[0]->app_secret;
            $this->sourceId = $config[0]->app_store_number;
        } else {
            $this->appKey = $res['config']['app_key'];
            $this->appService = $res['config']['app_secret'];
            $this->sourceId = $res['config']['app_store_number'];
        }
    }

    /**
     * 查询订单运费接口
     */
    public function deliverFee(array $data): array
    {
        try {
            $param = "/api/order/queryDeliverFee";
            $url = $this->baseUrl . $param;
            $res = $this->getHttpRequestWithPost($url, $data);
            return [HTTP_SUCCESS, $res['result']];
        } catch (Exception $e) {
            return [HTTP_UNAUTH, $e->getMessage()];
        }
    }

    /**
     * 新增订单
     */
    public function addOrder(array $data): array
    {
        try {
            $inf = "/api/order/addOrder";
            $url = $this->baseUrl . $inf;
            $data['callback'] = Request::domain() . "/callback";
            $res = $this->getHttpRequestWithPost($url, $data);
            return [HTTP_SUCCESS, $res['result']];
        } catch (Exception $e) {
            return [HTTP_UNAUTH, $e->getMessage()];
        }
    }

    /**重新发单
     * @param array $data
     * @return array
     */
    public function reAddOrder(array $data): array
    {
        try {
            $inf = "/api/order/reAddOrder";
            $url = $this->baseUrl . $inf;
            $res = $this->getHttpRequestWithPost($url, $data);
            return [HTTP_SUCCESS, $res['result']];
        } catch (Exception $e) {
            return [HTTP_UNAUTH, $e->getMessage()];
        }
    }

    /**
     * 查询运费后发单接口
     */
    public function addAfterQuery(array $data): array
    {
        try {
            $param = "/api/order/addAfterQuery";
            $url = $this->baseUrl . $param;
            $res = $this->getHttpRequestWithPost($url, $data);
            return [HTTP_SUCCESS, $res['result']];
        } catch (Exception $e) {
            return [HTTP_UNAUTH, $e->getMessage()];
        }
    }

    /**回调接口
     * @param array $data
     * @return array
     */
    public function callback(array $data)
    {
        $sign = $this->callback_sign($data);
        if ($data['signature'] != $sign) return [HTTP_UNAUTH, '签名有误！'];
        if ($data['order_status'] == 3) Order::update(['status' => 3], ['id' => $data['order_id']]);
        if ($data['order_status'] == 4) Order::update(['status' => 8], ['id' => $data['order_id']]);
        (new \app\shop_admin\model\Dada())->where(['client_id' => $data['client_id'], 'order_id' => $data['order_id']])->save($data);
    }

    /**构造请求参数
     * @param array $data
     */
    private function buildParam(array $data)
    {
        $requestParams['app_key'] = $this->appKey;
        $requestParams['body'] = implode($data);
        $requestParams['format'] = 'json';
        $requestParams['v'] = 1.0;
        $requestParams['source_id'] = $this->sourceId;
        $requestParams['timestamp'] = time();
        $requestParams['signature'] = $this->sign($requestParams);
        return $requestParams;
    }

    /**签名
     * @param array $data
     * @return string
     */
    private function sign(array $data)
    {
        ksort($data);
        $str = '';
        foreach ($data as $k => $v) {
            $str .= $k . $v;
        }
        $str = $this->appService . $str . $this->appService;
        return strtoupper(md5($str, FALSE));
    }

    /**取消订单
     *
     */
    public function formalCancel(array $data)
    {
        try {
            $inf = "/api/order/formalCancel";
            $url = $this->baseUrl . $inf;
            $this->getHttpRequestWithPost($url, $data);
        } catch (Exception $e) {
            return [HTTP_UNAUTH, $e->getMessage()];
        }
    }

    /**回调签名
     * @param array $data
     * @return string
     */
    public function callback_sign(array $data): string
    {
        ksort($data);
        $str = '';
        foreach ($data as $k => $v) {
            //client_id, order_id, update_time
            if (in_array($k, ['client_id', 'order_id', 'update_time']))
                $str .= $k . $v;
        }
        $str = $this->appService . $str . $this->appService;
        return strtoupper(md5($str, FALSE));
    }

    /**
     * 发送请求,POST
     * @param string $url 指定URL完整路径地址
     * @param array $data 请求的数据
     * @return bool|string
     */
    public function getHttpRequestWithPost(string $url, array $data)
    {
        $headers = ['Content-Type: application/json',];
        $data = $this->buildParam($data);
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 3);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $resp = curl_exec($curl);
        // var_dump(curl_error($curl));//如果在执行curl的过程中出现异常，可以打开此开关查看异常内容。
        $info = curl_getinfo($curl);
        curl_close($curl);

        if (isset($info['http_code']) && $info['http_code'] == 200) {
            return json_decode($resp, true);
        }
        return curl_error($curl);
    }
}